package com.amc.dao.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.amc.dao.IOrderDao;
import com.amc.dto.ComplaintView;
import com.amc.dto.FoodView;
import com.amc.dto.OrderView;
import com.amc.entity.Address;
import com.amc.entity.Complaint;
import com.amc.entity.Constant;
import com.amc.entity.Customer;
import com.amc.entity.Food;
import com.amc.entity.FoodType;
import com.amc.entity.Merchant;
import com.amc.entity.Order;
import com.amc.entity.OrderFood;

@Repository
public class OrderDaoImpl implements IOrderDao {
	@PersistenceContext
	private EntityManager em;

	public void setEm(EntityManager em) {
		this.em = em;
	}

	@Override
	public boolean placeOrder(OrderView order) {
		Order o = new Order();
		o.setAddress(em.find(Address.class, order.getAddressId()));
		o.setCustomer(em.find(Customer.class, order.getCustomerId()));
		o.setMerchant(em.find(Merchant.class, order.getMerchantId()));
		o.setOrderStatus(Constant.ORDER_WAIT_CONFIRM);
		o.setCreateTime(new Date());
		Set<OrderFood> set = new HashSet<>();
		List<FoodView> fv = order.getOrderFoods();
		for (FoodView f : fv) {
			Food food = em.find(Food.class, f.getFoodId());
			OrderFood orderFood = new OrderFood();
			orderFood.setFoodId(f.getFoodId());
			orderFood.setFoodMerchant(em.find(Merchant.class,
					order.getMerchantId()));
			orderFood.setFoodType(em.find(FoodType.class, food.getFoodType()
					.getTypeId()));
			orderFood.setOrderFoodCount(f.getCount());
			orderFood.setOrderFoodName(food.getFoodName());
			orderFood.setOrderFoodPic(food.getFoodPic());
			orderFood.setOrderFoodPrice(food.getFoodPrice());
			set.add(orderFood);
		}
		o.setOrderFood(set);
		boolean result = false;
		try {
			em.persist(o);
			result = true;
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("下订单错误");
		}
		return result;
	}

	@Override
	public List<OrderView> queryAllOrder(String customerId) {
		Query query = em.createQuery(
				"select o from Order o where o.customer.customerId=?")
				.setParameter(1, customerId);
		List<Order> orders = null;
		List<OrderView> orderView = new ArrayList<>();
		try {
			orders = query.getResultList();
//			long currentTime = new Date().getTime();
//			Date todayDate = new Date();
//			Date tempDate = new Date(todayDate.getHours(),
//					todayDate.getMinutes(), todayDate.getSeconds());
			for (Order order : orders) {

				OrderView ov = new OrderView(order.getOrderId(), order
						.getMerchant().getMerchantId(), order.getMerchant()
						.getMerchantName(),
						order.getCustomer().getCustomerId(), null, order
								.getAddress().getAddressId(), order
								.getAddress().getAddressName(), order
								.getAddress().getAddressContactTel(), order
								.getAddress().getAddressContactPerson(),
						order.getOrderStatus(), order.getCreateTime(),
						order.getConfirmTime(), order.getFinishTime(), order
								.getMerchant().getMerchantHeadpic());
				
//				System.out.println(tempDate.getTime() + " : " + order.getCreateTime().getTime());
//				if ((currentTime - (tempDate.getTime() - order.getCreateTime()
//						.getTime())) > 600000
//						&& ov.getOrderStatus() == Constant.ORDER_WAIT_CONFIRM) {
//					order.setOrderStatus(Constant.ORDER_CANCLE);
//					ov.setOrderStatus(Constant.ORDER_CANCLE);
//				}
				List<OrderFood> foods = new ArrayList<>(order.getOrderFood());
				List<FoodView> fvs = new ArrayList<>();
				for (OrderFood of : foods) {
					FoodView fv = new FoodView(of.getOrderFoodId(),
							of.getFoodId(), of.getOrderFoodName(),
							of.getOrderFoodPrice(), of.getOrderFoodPic(), of
									.getFoodType().getTypeId(),
							of.getOrderFoodCount());
					fvs.add(fv);
				}
				ov.setOrderFoods(fvs);
				orderView.add(ov);
			}

		} catch (Exception e) {
			System.out.println("订单列表获取错误");
		}
		return orderView;
	}

	@Override
	public OrderView queryOrderById(String orderId) {
		Order order = null;
		OrderView ov = null;
		try {
			order = em.find(Order.class, orderId);
//			long currentTime = new Date().getTime();
			ov = new OrderView(order.getOrderId(), order.getMerchant()
					.getMerchantId(), order.getMerchant().getMerchantName(),
					order.getCustomer().getCustomerId(), null, order
							.getAddress().getAddressId(), order.getAddress()
							.getAddressName(), order.getAddress()
							.getAddressContactTel(), order.getAddress()
							.getAddressContactPerson(), order.getOrderStatus(),
					order.getCreateTime(), order.getConfirmTime(),
					order.getFinishTime(), order.getMerchant()
							.getMerchantHeadpic());
//			System.out.println(currentTime + "................"
//					+ order.getCreateTime().getTime());
//			if ((currentTime - order.getCreateTime().getTime()) > 600000
//					&& ov.getOrderStatus() == Constant.ORDER_WAIT_CONFIRM) {
//				order.setOrderStatus(Constant.ORDER_CANCLE);
//				ov.setOrderStatus(Constant.ORDER_CANCLE);
//			}
			List<OrderFood> foods = new ArrayList<>(order.getOrderFood());
			List<FoodView> fvs = new ArrayList<>();
			for (OrderFood of : foods) {
				FoodView fv = new FoodView(of.getOrderFoodId(), of.getFoodId(),
						of.getOrderFoodName(), of.getOrderFoodPrice(),
						of.getOrderFoodPic(), of.getFoodType().getTypeId(),
						of.getOrderFoodCount());
				fvs.add(fv);
			}
			ov.setOrderFoods(fvs);
		} catch (Exception e) {
			System.out.println("订单详情查询失败");
		}
		return ov;
	}

	@Override
	public boolean receiptOrder(String orderId) {
		boolean result = false;
		try {
			Order order = em.find(Order.class, orderId);
			System.out.println(order.getOrderStatus());
			order.setOrderStatus(Constant.ORDER_FINISH);
			result = true;
		} catch (Exception e) {
			System.out.println("确认订单完成失败");
		}
		return result;
	}

	@Override
	public boolean cancellOrder(String orderId) {
		boolean result = false;
		try {
			Order order = em.find(Order.class, orderId);
			em.remove(order);
			result = true;
		} catch (Exception e) {
			System.out.println("订单取消失败");
		}
		return result;
	}

	@Override
	public boolean complaintMerchant(ComplaintView complaint) {
		Complaint c = new Complaint(null, em.find(Merchant.class,
				complaint.getMerchantId()), em.find(Customer.class,
				complaint.getCustomerId()), complaint.getComplaintText(),
				new Date());
		boolean result = false;
		try {
			em.persist(c);
			result = true;
		} catch (Exception e) {
			System.out.println("投诉失败");
		}
		return result;
	}

	@Override
	public FoodView queryFood(String foodId) {
		Query query = em.createQuery("select f from Food f where f.foodId=?")
				.setParameter(1, foodId);
		FoodView foodView = new FoodView();
		try {
			Food food = (Food) query.getSingleResult();
			foodView = new FoodView(null, food.getFoodId(), food.getFoodName(),
					food.getFoodPrice(), food.getFoodPic(), food.getFoodType()
							.getTypeId(), 1);
		} catch (Exception e) {

		}
		return foodView;
	}

	@Override
	public boolean refuseOrder(String orderId) {
		boolean result = false;
		try {
			Order o = em.find(Order.class, orderId);
			if (o.getOrderStatus() == 0) {
				o.setOrderStatus(Constant.ORDER_CANCLE);
				result = true;
			} else {
				System.out.println("订单已被确认或完成，无法取消");
			}
		} catch (Exception e) {
			System.out.println("订单取消失败");
		}
		return result;
	}

}
